package com.ruiao.car.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by jsonval on 2019/10/24.
 */
public class AesUtils {

    static byte[] key = "N76$Yyl5AwP8yabW".getBytes();

    // 加密
    public static String Encrypt(String sSrc) throws Exception {
        // byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return URLEncoder.encode( new Base64().encodeToString(encrypted) );//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }


    // 解密
    public static String Decrypt(String sSrc) throws Exception {
        try {
            sSrc = URLDecoder.decode(sSrc);
            SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }


    public static void main(String args[]) throws Exception{

        String origin = "gi9otzuyxkuljn4zp9t0";
        String encrypt = AesUtils.Encrypt(origin);
        System.out.println(encrypt);
        String decrypt = AesUtils.Decrypt(encrypt);
        System.out.println(decrypt);

    }


}
